<template>
  <div class="qm-user-select">
    <div class="list">
      <a href="#" class="item-link" @click="opened = true">
        <div class="item-content">
          <div class="item-inner">
            <div class="item-title">{{label}}</div>
            <div class="item-after">{{selText}}</div>
          </div>
        </div>
      </a>
    </div>
    <!-- 弹出框 -->
    <f7-popup swipe-to-close :opened="opened" class="qm-popup">
      <f7-page class="page-with-subnavbar">
        <!-- 头部 -->
        <f7-navbar :title="label">
          <f7-nav-right>
            <i class="f7-icons" @click="opened = false">xmark</i>
          </f7-nav-right>
          <!-- 搜索 -->
          <f7-subnavbar :inner="false">
            <f7-searchbar
              placeholder="请输入关键词"
              :backdrop="true"
              @searchbar:enable="onSearchbarEnable"
              @searchbar:disable="onSearchbarDisable"
              @input="onSearchbarInput">
            </f7-searchbar>
          </f7-subnavbar>
        </f7-navbar>
        <!-- 单选或复选列表 -->
        <f7-list class="qm-select">
          <f7-list-item
            v-for="user in usersData"
            :key="user.value"
            name="user-item"
            v-bind="selItemStyle"
            :value="user.value"
            :title="`${user.label}（${user.loginId}）`"
            :checked="isChecked(user)"
            @change="(e) => onChecked(e, user)">
          </f7-list-item>
        </f7-list>
        <!-- tags -->
        <div class="qm-user-tags" v-if="multiple">
          <van-tag
            v-for="(tag, i) in tags"
            :key="tag.value"
            closeable
            size="medium"
            type="primary"
            @close="() => onTagClose(i)">
            {{`${tag.label}（${tag.loginId}）`}}
          </van-tag>
        </div>
      </f7-page>
    </f7-popup>
  </div>
</template>

<script>
import { Tag } from "vant";

export default {
  name: "qm-user-select",
  components: {
    [Tag.name]: Tag
  },
  model: {
    prop: "value",
    event: "change"
  },
  props: {
    value: {
      type: [Object, Array]
    },
    label: {
      type: String,
      default: "用户选择"
    },
    // 多选
    multiple: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    // 用户项样式
    selItemStyle() {
      return ({
        checkbox: this.multiple,
        radio: !this.multiple
      })
    },
    inpType() {
      return this.multiple ? "checkbox" : "radio";
    },
    // 选中显示文本
    selText() {
      if (this.multiple) {
        return Array.isArray(this.value) ? this.value.map(user => `${user.label}（${user.loginId}）`).join(",") : "";
      } else {
        return this.checkType(this.value) === "object" ? (`${this.value.label}（${this.value.loginId}）` || "") : "";
      }
    },
    tags() {
      if (this.multiple && Array.isArray(this.value)) {
        return this.value;
      } else {
        return [];
      }
    },
  },
  created() {
    this.remote("");

    if (this.multiple && !Array.isArray(this.value)) {
      this.$emit("change", []);
    }

    if (!this.multiple && Array.isArray(this.value)) {
      this.$emit("change", null);
    }
  },
  data() {
    return {
      opened: false, // 弹出框显示与隐藏
      selected: [],
      timer: null,
      usersData: []
    }
  },
  methods: {
    // 点击搜索，显示搜索背景
    onSearchbarEnable(searchbar) {
      searchbar.backdropEl.classList.add("searchbar-backdrop-in");
    },
    // 退出搜索，隐藏搜索背景
    onSearchbarDisable(searchbar) {
      this.remote("");
      searchbar.backdropEl.classList.remove("searchbar-backdrop-in");
    },
    // 搜索框检索
    onSearchbarInput(e) {
      const value = e.target.value;
      const backdropEle = document.querySelector(".qm-popup .searchbar-backdrop");
      // 根据搜索框是否有文字，控制搜索背景显示与隐藏
      if (value.length) {
        backdropEle.classList.contains("searchbar-backdrop-in") && backdropEle.classList.remove("searchbar-backdrop-in");
      } else {
        !backdropEle.classList.contains("searchbar-backdrop-in") && backdropEle.classList.add("searchbar-backdrop-in");
      }
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.remote(value);
      }, 300)
    },
    // 单选或复选框选中
    onChecked(e, user) {
      const { checked } = e.target;
      // 单选
      if (!this.multiple) {
        this.$emit("change", Object.assign({}, user));
        return;
      }
      let values = Array.from(Array.isArray(this.value) ? this.value : []);
      if(checked) {
        (!values.length || values.some(ele => ele.value !== user.value)) && values.push(user);
      } else {
        values = values.filter(ele => ele.value !== user.value);
      }
      this.$emit("change", values);
    },
    // 远程检索
    remote(val) {
      return new Promise((resolve, reject) => {
        this.$f7.request({
          url: "/admin/sysRole/setUsers/userSelect2",
          method: "get",
          data: { term: val },
          success: res => {
            res = JSON.parse(res);
            const usersData = res.data.map(user => ({
              value: user.userId,
              userId: user.userId,
              label: user.userName,
              loginId: user.loginId, 
            }));
            this.usersData.splice(0, this.usersData.length, ...usersData);
            resolve();
          },
          error(err) {
            console.log(err);
            reject(err);
          }
        })
      })
    },
    // 点击标签删除
    onTagClose(idx) {
      let value = Array.from(this.value);
      value.splice(idx, 1);
      this.$emit("change", value);
    },
    // 是否选中
    isChecked(user) {
      if (this.multiple) {
        return Array.isArray(this.value) && this.value.some(ele => ele?.value === user.value);
      } else {
        return this.checkType(this.value) === "object" && this.value.value === user.value;
      }
    },
    checkType(val) {
      return Object.prototype.toString.call(val).replace(/(\[|\]|object\s)/gi, "").toLowerCase();
    }
  },
  watch: {
    multiple(val) {
      this.$emit("change", val ? [] : null);
    }
  }
}
</script>

<style lang="less" scoped>
.qm-user-select {
  ::v-deep {
    // 选中文本显示
    .item-after {
      max-width: 70%;
      overflow: hidden;
      text-overflow: ellipsis;
      position: relative;
      display: block;
    }

    > .list {
      margin: 0;
    }
  }
}
// 选中项
.list.qm-select {
  ::v-deep .item-inner {
    &::before {
      content: "";
      position: absolute;
      background-color: rgba(0, 0, 0, 0.22);
      display: block;
      z-index: 15;
      top: auto;
      right: auto;
      bottom: 0;
      left: 0;
      height: 1px;
      width: 100%;
      transform-origin: 50% 100%;
      transform: scaleY(0.5);
    }
  }
}

// tag
.qm-user-tags {
  padding-left: calc(var(--f7-list-item-padding-horizontal) + var(--f7-safe-area-left));

  .van-tag {
    margin: 2px 0 2px 6px;
  }
}
</style>
